/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.pc9.pswing.util;

import br.com.pc9.pswing.components.filebrowser.PFileView;
import java.awt.Image;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author paulocanedo
 */
public class WindowsUtil implements OperationSystemUtilInterface {

    private UserFolders userFolders = new WindowsUserFolders();
    private ImageresReader imageresReader;
    private Map<String, File> files = new HashMap<String, File>();
    private String queryBin = "reg query";
    private String registerLocation = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";

    public WindowsUtil() {
    }

    @Override
    public List<PFileView> getFavoritePlaces() throws IOException {
        try {
            File folder = getFile("Favorites");
            File[] listFiles = folder.listFiles(new FileFilter() {

                @Override
                public boolean accept(File pathname) {
                    return pathname.isDirectory();
                }
            });

            List<PFileView> list = new ArrayList<PFileView>();
            for (File f : listFiles) {
                list.add(new PFileView(f));
            }
            return list;
        } catch (InterruptedException ex) {
            Logger.getLogger(WindowsUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new ArrayList<PFileView>();
    }

    @Override
    public UserFolders getUserFolders() throws IOException {
        return userFolders;
    }

    private class WindowsUserFolders implements UserFolders {

        public WindowsUserFolders() {
        }

        @Override
        public File getDesktopFolder() throws Exception {
            return getFile("Desktop");
        }

        @Override
        public File getDocumentFolder() throws Exception {
            return getFile("Personal");
        }

        @Override
        public File getMusicFolder() throws Exception {
            return getFile("My Music");
        }

        @Override
        public File getPicturesFolder() throws Exception {
            return getFile("My Pictures");
        }

        @Override
        public File getPublicShareFolder() {
            return null;
        }

        @Override
        public File getVideosFolder() throws Exception {
            return getFile("My Video");
        }

        @Override
        public File getTemplateFolder() throws Exception {
            return getFile("Templates");
        }

        @Override
        public File getDownloadsFolder() throws Exception {
            return getFile("{374DE290-123F-4565-9164-39C4925E467B}");
        }
    }

    @Override
    public String getThemeName() throws Exception {
        return "Default Windows Theme";
    }

    @Override
    public Icon getSystemIcon(String category, String name, int size) {
//        String keyName = category + "." + name;
//        Icon iconCache = GenericIconFactory.getIconInCache(keyName);
//        if (iconCache != null) {
//            return iconCache;
//        }
//
//        try {
//            if (imageresReader == null) {
//                imageresReader = ImageresReader.getInstance();
//            }
//
//            Image image = null;
//            if (name.equals("user-home")) {
//                image = imageresReader.getImage(ImageresReader.USER_FOLDER);
//            } else if (name.equals("folder")) {
//                image = imageresReader.getImage(ImageresReader.DEFAULT_FOLDER);
//            } else if (name.equals("folder-documents")) {
//                image = imageresReader.getImage(ImageresReader.DOCUMENTS_FOLDER);
//            } else if (name.equals("folder-downloads")) {
//                image = imageresReader.getImage(ImageresReader.DOWNLOAD_FOLDER);
//            } else if (name.equals("folder-pictures")) {
//                image = imageresReader.getImage(ImageresReader.PICTURES_FOLDER);
//            } else if (name.equals("folder-videos")) {
//                image = imageresReader.getImage(ImageresReader.MOVIES_FOLDER);
//            } else if (name.equals("folder-music")) {
//                image = imageresReader.getImage(ImageresReader.MUSIC_FOLDER);
//            } else if (name.equals("gnome-fs-regular")) {
//                image = imageresReader.getImage(ImageresReader.FILE_SYSTEM);
//            }
//
//            if (image != null) {
//                Image scaledInstance = image.getScaledInstance(size, size, Image.SCALE_SMOOTH);
//
//                return GenericIconFactory.setIconInCache(keyName, new ImageIcon(scaledInstance));
//            }
//        } catch (Exception ex) {
//        }
        return GenericIconFactory.getSystemIcon(category, name, size);
    }

    public static String getWindowsPath() {
        return System.getenv("WINDIR");
    }

    public static String getWindowsDrive() {
        return System.getenv("SYSTEMDRIVE") + "\\";
    }

    private String query(String registerLocation, String field) throws IOException, InterruptedException {
        String command = String.format("%s \"%s\" /v \"%s\"", queryBin, registerLocation, field);
        Process exec = Runtime.getRuntime().exec(command);
        exec.waitFor();

        String text = getText(exec.getInputStream()).trim();
        int firstLineIndex = text.indexOf("\n");
        if (firstLineIndex > 0) {
            text = text.substring(firstLineIndex + 1);//ignore first line
            String separator = "    ";
            int lastIndexOf = text.lastIndexOf(separator);
            if (lastIndexOf > 0) {
                return text.substring(lastIndexOf + separator.length());
            }
        }
        return null;
    }

    private static String getText(InputStream stream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        return sb.toString();
    }

    private File getFile(String key) throws IOException, InterruptedException {
        File file = files.get(key);
        if (file == null) {
            String fileName = query(registerLocation, key);
            if (fileName != null) {
                String keyname = "﻿REG_SZ ";
                int indexOf = fileName.indexOf("\t");
                if (indexOf >= 0) {
                    fileName = fileName.substring(indexOf + keyname.length());
                }
            }
            if (fileName != null) {
                files.put(key, file = new File(fileName));
            }
        }
        return file;
    }
    
}
